<?php

namespace app\admin\controller\dev;

use app\admin\controller\Admin;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use think\exception\ValidateException;
use think\facade\Log;

class Doc extends Admin
{
    /**
     * deep seek api 调用测试
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function deepSeekTest(): \think\response\Json
    {
        $content = $this->request->post('content');

        $client = new Client();

        try {
            $apiKey = config('rds.deepseek.api_key');
            $apiUrl = 'https://api.deepseek.com/v1/chat/completions';

            if (empty($apiKey)) {
                throw new ValidateException('API密钥未配置');
            }

            $header = [
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ];

            $json = [
                'messages' => [
                    ['role' => 'user', 'content' => $content]
                ],
                'model' => 'deepseek-chat',
                'max_tokens' => 2048,
                'temperature' => 0.7
            ];
            $response = $client->post($apiUrl, ['headers' => $header, 'json' => $json]);

            $responseBody = $response->getBody()->getContents();
            $result = json_decode($responseBody, true);

            // 记录完整响应日志
            Log::info('DeepSeek API Response: ' . print_r([
                    'status' => $response->getStatusCode(),
                    'headers' => $response->getHeaders(),
                    'body' => $result
                ], true));

            if ($response->getStatusCode() === 200 && isset($result['choices'][0]['message']['content'])) {
                return $this->success([
                    'data' => trim($result['choices'][0]['message']['content'])
                ]);
            }
            throw new ValidateException('API返回异常响应: ' . ($result['error']['message'] ?? '未知错误'));
        } catch (RequestException $e) {
            // 处理 Guzzle 请求异常
            $errorMessage = 'API请求失败: ';
            if ($e->hasResponse()) {
                $response = $e->getResponse();
                $statusCode = $response->getStatusCode();
                $errorBody = $response->getBody()->getContents();

                Log::error("DeepSeek API Error [{$statusCode}]: " . $errorBody);
                $errorMessage .= "[{$statusCode}] " . ($response->getReasonPhrase() ?? '未知错误');
            } else {
                Log::error('DeepSeek Network Error: ' . $e->getMessage());
                $errorMessage .= $e->getMessage();
            }
            return $this->error(['code' => 500, 'message' => $errorMessage]);
        } catch (\Exception $e) {
            return $this->error(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

}